<?php 
/**
 *内容管理
*/

namespace xhadmin\service\admin;

use xhadmin\CommonService;
use xhadmin\db\Content;
use xhadmin\db\Catagory;
use xhadmin\db\Extend;
use xhadmin\db\BaseDb;
use xhadmin\db\Position;
use app\admin\db\Field;
use think\facade\Log;

class ContentService extends CommonService {


	/*
 	* @Description  内容管理列表数据
 	* @param (输入参数：)  {array}        where 查询条件
 	* @param (输入参数：)  {int}          limit 分页参数
 	* @param (输入参数：)  {String}       field 查询字段
 	* @param (输入参数：)  {String}       orderby 排序字段
 	* @return (返回参数：) {array}        分页数据集
 	*/
	public static function pageList($where=[],$limit,$field='*',$orderby=''){
		try{
			$list = Content::loadList($where,$limit,$field,$orderby);
			$count = Content::countList($where);
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
		return ['list'=>$list,'count'=>$count];
	}


	/*
 	* @Description  添加
 	* @param (输入参数：)  {array}        data 原始数据
 	* @return (返回参数：) {bool}        
 	*/
	public static function add($data){
		try{
			//数据验证
			$rule = [
				'title'=>['require'],
				'class_id'=>['require'],
			];
			//数据错误提示
			$msg = [
				'title.require'=>'文章标题不能为空',
				'class_id.require'=>'所属分类不能为空',
			];
			self::validate($rule,$data,$msg);

			$data['create_time'] = time();
			$res = Content::createData($data);
			if($res){
				$data['content_id'] = $res;
				Content::editWhere(['content_id'=>$res],['sortid'=>$res]);
				self::saveExtData($data);
			}
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
		return $res;
	}


	/*
 	* @Description  修改
 	* @param (输入参数：)  {array}        data 原始数据
 	* @return (返回参数：) {bool}        
 	*/
	public static function update($data){
		try{
			//数据验证
			$rule = [
				'title'=>['require'],
				'class_id'=>['require'],
			];
			$msg = [
				'title.require'=>'文章标题不能为空',
				'class_id.require'=>'所属分类不能为空',
			];
			self::validate($rule,$data,$msg);

			$data['create_time'] = strtotime($data['create_time']);
			$res = Content::edit($data);
			self::saveExtData($data);
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
		return $res;
	}
	
	
	//更新拓展表信息
	 public static function saveExtData($data){
        $classId = $data['class_id'];
        $fieldsetInfo = Catagory::getInfo($classId);	
		try{
			if(!empty($fieldsetInfo['module_id'])){
				$fieldList = Field::loadList(['extend_id'=>$fieldsetInfo['module_id'],'status'=>1]);
				foreach($fieldList as $k=>$v){
					if($v['type'] == 7){
						$data[$v['field']] = strtotime($data[$v['field']]);
					}
				}
				$extInfo = Extend::getInfo($fieldsetInfo['module_id']);
				BaseDb::setTableName('ext_'.$extInfo['table_name']);
				BaseDb::setPk('content_id');
					
				if(!BaseDb::getInfo($data['content_id'])){
					BaseDb::createData($data);
				}else{
					Log::info($data);
					BaseDb::editWhere(['content_id'=>$data['content_id']],$data);
				}	
			}
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
        
        return true;
    }

	/*
 	* @Description  删除
 	* @param (输入参数：)  {array}        where 删除条件
 	* @return (返回参数：) {bool}        
 	*/
	public static function delete($where){
		try{
			$res = Content::delete($where);
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
		return $res;
	}
	
	//生成树级结构列表 递归的方法
	public static function getSubClass($pid){
		$list = Catagory::loadList(['pid'=>$pid],100,$field="class_id,pid,class_name,class_id as childs",'sortid asc,class_id asc');
		foreach($list as $key=>$val){
			$sublist = Catagory::loadList(['pid'=>$val['class_id']],100,$field="class_id,pid,class_name,class_id as childs",'sortid asc,class_id asc');
			if($sublist){
				$childs = \app\index\facade\Cat::getSubClassId($val['class_id']);
				$list[$key]['childs'] = $childs;
				$list[$key]['spread'] = !is_null(config('content_menu_status')) ? config('content_menu_status') : true;
				$list[$key]['children'] = self::getSubClass($val['class_id']);
				foreach($list[$key]['children'] as $k=>$v){
					if(!$v['childs']){
						$list[$key]['children'][$k]['childs'] = $v['class_id'];
					}
				}	
			}
		}
		return $list;
	}
	
	//获取推荐位的名称
	public static function getPositionName($position,$content_id){
		if(!$position) {
			return;
		}
		$where['position_id'] = explode(',',ltrim($position,','));
		$list = Position::loadList($where);
		
		if($list){
			foreach($list as $k=>$v){
				$title .= '<a style="color:red" title="点击删除" href="javascript:void(0)" onclick="CodeGoods.delPosition('.$v['position_id'].','.$content_id.')">'.$v['title'].'</a>,';
			}
			
		}
		$title = rtrim($title,',');
		return '<font color="red">['.$title.']</font>';
	}
	
	//批量设置推荐位
	public static function setPosition($content_id,$position_id){
	
		try{
			$contentInfo = Content::getInfo($content_id);
			if($contentInfo){
				if(strpos($contentInfo['position'],$position_id) == false){
					$data['position'] = $contentInfo['position'].','.$position_id;
					$data['content_id'] = $content_id;
					Content::edit($data);
				}
			}
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
			
		return $reset;	
	}
	
	//批量设置推荐位
	public static function delPosition($content_id,$position_id){
	
		try{
			$contentInfo = Content::getInfo($content_id);
			if($contentInfo['position']){
				$data['position'] = rtrim(str_replace($position_id.',','',$contentInfo['position'].','),',');
				$data['content_id'] = $content_id;
				Content::edit($data);
			}
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
			
		return $reset;	
	}
	
	//获取拓展内容信息
	public static function getExtDataInfo($classId,$content_id){
		if(empty($classId) || empty($content_id)){
			return;
		}
		
		$extInfo = Extend::getInfo($classId);
		BaseDb::setTableName('ext_'.$extInfo['table_name']);
		BaseDb::setPk('content_id');
		
		$extInfo = BaseDb::getInfo($content_id);
		return $extInfo;
		
	}




}

